/**
 * 公共js方法
 */

 /*
 获取所有参数
 notShare：需要去掉canAppShare参数传true，不传或者传false表示不需要去掉
 */
var getParams = function(notShare){
  var path = window.location.href;
  if(path.indexOf("?") != -1){
    if(notShare){
      var params = path.split("?")[1];
      if(params.indexOf("&canAppShare=1") != -1){
        params = params.replace("&canAppShare=1","");
      }else if(params.indexOf("canAppShare=1") != -1){
        params = params.replace("canAppShare=1","");
      }
      return params;
    }else{
      return path.split("?")[1];
    }
  }else{
    return "";
  }
};
/*
 获取所有参数,包括？号，用于去掉参数，即调用subStringParams，传该方法返回的值
 notShare：需要去掉canAppShare参数传true，不传或者传false表示不需要去掉
 */
var getParamsSection = function(notShare){
  var params = getParams(notShare);
  if(params){
    params = "?" + params;
  }

  return params;
};
/*
根据参数key获取参数value
*/
var getParamValue = function(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
	var r = window.location.search.substr(1).match(reg);
	if (r!=null) return (r[2]); return null;
};

/*
常量数据
*/
var baseUrl = /pretest\_dzg/.test(window.location.href) ? '/pretest_dzg' : '/dzg';
var Constants = {
  //ESOP ws/rest接口host。因为跨域问题，测试时(本机和120上)，通过govGroupH5访问DZG RPC接口。正式环境，直接访问RPC接口。SVN代码请保留正式环境代码，即直接访问DZG RPC
  //ws api
  // rpcEsopHost:"../../../govGroupH5/ws/",
  // rpcEsopHost: "/dzg/rpc/esop/ws/",
  rpcEsopHost: baseUrl + '/api/v2/business/rpc/esop/ws/', // 改为不直接访问rpc的rest透传接口
  //rest api
  // rpcCrmHost:"../../../govGroupH5/rest/",
  // rpcCrmHost: "/dzg/rpc/esop/rest/",
  rpcCrmHost: baseUrl + '/api/v2/business/rpc/esop/rest/', // 改为不直接访问rpc的rest透传接口
  restHost: baseUrl + '/api/v2/business/rpc/',
  //campus broadband00
  campusBdRequestHost: '../../govGroupH5/bdRequest/',
  apiV2HostRest: baseUrl + '/api/v2/business/rpc/esop/rest/', // API REST接口
  apiV2Host: baseUrl + '/api/v2/',
  number:/^[0-9]*$/, //纯数字
  cmccMobileReg: /^(13[4-9]|14[7]|15[012789]|18[23478]|209|17[8])\d{8}$/, //移动号码段
  COOKIEGOVINDEXURLPREFIX : "govindexurl" //政企专区首页url地址保存到cookie用
};

var getDomainUrl = function(){
    /*var curWwwPath=window.document.location.href;
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    var domainUrl=curWwwPath.substring(0,pos);*/
    var domainUrl = window.location.origin;
    return domainUrl;
}


var objToArr = function(obj){
  var arr = new Array();
  if(obj instanceof Array){
    arr = obj;
  }else if(obj instanceof Object){
    arr.push(obj);
  }
  return arr;
}

/*
 去掉不需要的参数
 params：所有的参数串
 paramKey：需要被截取的参数key
 */
var subStringParams = function(params,paramKey){
  if(params && paramKey){
    var allParams = params;
    //1.
    var index = params.indexOf("&"+paramKey+"=");
    if(index != -1){//不是第一个参数：……&id=1……
      params = params.substring(index+1);//结果：id=1……
      //2.
      var index2 = params.indexOf("&");
      if(index2 != -1){//不是最后一个参数：……&id=1&name=……
          params = params.substring(0,index2);//结果：id=1
      }
      //3.
      params = allParams.replace("&"+params,"");
    }else{
      if(params.indexOf("?"+paramKey+"=") != -1){//是第一个参数：?id=1……
        params = "?" + params;
        allParams = params;
        //1.
        var index2 = params.indexOf("&");
        if(index2 != -1){//不是最后一个参数：?id=1&name=……
          params = params.substring(0,index2);//结果：?id=1
          params = allParams.replace(params+"&","");//结果：name=……
        }else{//是最后一个参数：?id=1
          params = allParams.replace(params,"");//结果：无参数了
        }
      }
    }
  }

  return params;
}

/*
获取从宽带预约页面返回首页的参数串
*/
var getToIndexParam = function(bd_type) {
  var myParam = "";
  if(bd_type == 3){//校园宽带预约
    myParam = getParams();
  }else if(bd_type == 2){//商务动力宽带预约
    var canAppShare = getParamValue("canAppShare");
    var canIndexShare = getParamValue("canIndexShare");

    if(canAppShare == 1 && canIndexShare !=1){
      myParam = getParams(true);//首页不可分享
    } else if(canIndexShare ==1){
      myParam = getParams();
      myParam = subStringParams(myParam,"canIndexShare");
    } else {
      myParam = getParams();
    }
  }else{//大市场宽带预约
    myParam = getParams();
  }

  myParam = subStringParams(myParam,"bd_type");
  myParam = subStringParams(myParam,"id");
  myParam = subStringParams(myParam,"name");

  return myParam;
};

var getEmpCode = function(){
	return getParamValue("EmpCode");
	//return "ai_hanfeng";
}

var getMobile = function(){
	var token = getParamValue("token");
	
	if(token){
		if(token.length >= 11){
			return token.substr(token.length - 11,11);
		}
		return token;
	}
	return "";
}

var getToken = function(){
  var token = getParamValue("token");
  if(token){
   return token;
  }else{
    return "20160706112233445513890355933";
  }
}

//固定格式的“动态条+文本”，(loadingbar,true/open)仅控制开关，不控制内容。(loadingbar,open,result,msg)控制显示的内容，如果result为false则是进度条+内容，为true则只有内容，没有进度条，用于显示结果
var showLoadingBar = function(loadingbar,open,result,msg,isdisabled){
   
    if(open){
    		if(result){
    			if((msg==null)||(msg=="")){
    				msg="需要显示的内容为空";
    			}
    			loadingbar.html(msg);		
    			
    		}else{
    			if(msg){
            if(isdisabled){
              $("body").find("button").addClass("am-disabled");
            }else{
              $("body").find("button").removeClass("am-disabled");
            }
    				loadingbar.html("<i class='am-icon-spinner am-icon-spin' aria-hidden='true'></i>&nbsp&nbsp"+msg);	
    			}
    		}
    	

       	if(loadingbar.hasClass("am-hide")){
		    loadingbar.removeClass("am-hide");
       	}
    }else{
	  	if(!loadingbar.hasClass("am-hide")){
		    loadingbar.addClass("am-hide");
	  	}
    }

};

/**
 * 设置cookie值
 * @param c_name
 * @param value
 * @param expiredays
 * @param path：可在同一应用服务器内共享cookie方法：设置cookie.setPath("/");
 * @returns
 */
var setCookie = function(c_name,value,expiredays,path){
  var expires = "";
  if(expiredays && expiredays > 0){
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    expires = exdate.toGMTString();
  }
  document.cookie = c_name + "=" + escape(value) + (expires ? ";expires="+expires : "") + (path ? ";path="+path : "");
};
/**
 * 从cookie取值
 * @param c_name
 * @returns
 */
var getCookie = function(c_name){
  var mycookie = document.cookie;
  if(c_name && mycookie && mycookie.length > 0){
    var c_start = mycookie.indexOf(c_name + "=");
    if(c_start != -1){ 
        c_start = c_start + c_name.length + 1;
        var c_end = mycookie.indexOf(";",c_start);
        if (c_end == -1)
          c_end = mycookie.length;
        return unescape(mycookie.substring(c_start,c_end));
      } 
  }
  return "";
};
/**
 * 删除cookie值
 * @param c_name
 * @returns
 */
var deleteCookie = function(c_name){
  if(c_name){
    var date = new Date(); 
    date.setTime(date.getTime()-10000); 
    document.cookie = c_name + "=delete;expires=" + date.toGMTString(); 
  }
};

var showMsg = function(id,msg){
	if((msg==null)||(msg==""))
		msg="需要显示的信息为空";
	id.html(msg);
	if(id.hasClass("am-hide")){
		id.removeClass("am-hide");
	}
}

var show = function(id){
	if(id.hasClass("am-hide")){
		id.removeClass("am-hide");
	}
}


var hide = function(id){
	if(!id.hasClass("am-hide")){
		id.addClass("am-hide");
	}
};

/*
发送验证码
*/
var sendSms = function(tel){
  // var params = {
  //   phoneNo: tel,
  //   passMode: '0'
  // };
  // var url = "../../../govBroadbandH5/getVerifyCode";
  var params = '?phoneNumber=' + tel + '&smsType=9&empCode=' + getParamValue('empCode') + '&token=' + getParamValue('token');
  var url = Constants.apiV2Host + 'sms/send' + params;
  $.ajax({
    type: "get",
    url: url,
    dataType: "json",
    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      $('#modal').modal('close');
      // if(data && data.res_code != 0000){
      //   alert(data.res_msg);
      // }
      if(data && '' + data.ResultCode !== '1000'){
        alert("发送验证码失败！"+data.Message);
        return;
      }
      alert("发送验证码成功！");
    },
    error : function(textStatus) {
      $('#modal').modal('close');
      alert("发送验证码失败！");
    }
  });
};


/*
发送验证码
*/
var verifySms = function(tel,code,callback){
  // var params = {
	//   phoneNo: tel,
	//   verifyCode: code
  // };
  // var url = "../../../govBroadbandH5/verifySms";
  var url = Constants.apiV2Host + 'sms/validate?phoneNumber=' + tel + '&smsCode=' + code + '&empCode=' + getParamValue('EmpCode') + '&smsType=9&token=' + getParamValue('token');
  $.ajax({
    type: "get",
    url: url,
    dataType: "json",
    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      $('#modal').modal('close');
      console.info(data);
      if(data && '' + data.ResultCode != '1000'){
        alert("短信验证码校验失败！"+data.Message);
        return;
      }
      callback();
    },
    error : function(textStatus) {
      $('#modal').modal('close');
      alert("短信验证码校验失败！");
    }
  });
};

/*
封装restful请求
*/
var sendRestPostAjax = function(params,reqUrl,successFun,loadingBarId){
  console.log("request url = "+reqUrl);
  console.log("request params = "+JSON.stringify(params));
  $.ajax({
    type: "post",
    contentType: "application/json",
    data: JSON.stringify(params),
    url: reqUrl,
    dataType: "json",
    async: true,
    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      showLoadingBar($('#'+loadingBarId),false);
      console.log("data = "+JSON.stringify(data));
      var returnData = data.ROOT;
      console.info(returnData);
      
      if(returnData.RETURN_CODE!=0){
    	var msg = returnData.DETAIL_MSG?returnData.DETAIL_MSG:returnData.RETURN_MSG;
          if(reqUrl.indexOf("s4000Cfm")!=-1 && returnData.RETURN_CODE==1005){
              var dataStr = JSON.stringify(data);
              if(dataStr.indexOf("timed out")!=-1 || dataStr.indexOf("CRM_TEMPLATE")!=-1
                  || dataStr.indexOf("中间件")!=-1 || dataStr.indexOf("系统忙")!=-1){
                  msg = ("调用服务超时，请核实是否办理成功。");
              }
          }


          alert(msg);
        console.log("获取RPC接口返回失败！code:"+returnData.RETURN_CODE);
        return;
      }
      
      successFun(returnData.OUT_DATA);
    },
    error : function(textStatus) {
      showLoadingBar($('#'+loadingBarId),false);
      alert("网络或服务器异常，请稍后再试！");
      console.info("request error:");
    }
  });
};

var sendRestPostAjaxWithModal = function(params,reqUrl,successFun,modalObj){
	  console.log("request url = "+reqUrl);
	  console.log("request params = "+JSON.stringify(params));
	  modalObj.modal('open');
	  
	  $.ajax({
	    type: "post",
	    contentType: "application/json",
	    data: JSON.stringify(params),
	    url: reqUrl,
	    dataType: "json",
	    async: true,
	    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
	      modalObj.modal('close');
	      console.log("data = "+JSON.stringify(data));
	      var returnData = data.ROOT;
	      console.info(returnData);
	      
	      if(returnData.RETURN_CODE!=0){
	    	var msg = returnData.DETAIL_MSG?returnData.DETAIL_MSG:returnData.RETURN_MSG;
	        if(reqUrl.indexOf("s4000Cfm")!=-1 && returnData.RETURN_CODE==1005){
                var dataStr = JSON.stringify(data);
                if(dataStr.indexOf("timed out")!=-1 || dataStr.indexOf("CRM_TEMPLATE")!=-1
                    || dataStr.indexOf("中间件")!=-1 || dataStr.indexOf("系统忙")!=-1){
                    msg = ("调用服务超时，请核实是否办理成功。");
                }
            }
            alert(msg);
	        console.log("获取RPC接口返回失败！code:"+returnData.RETURN_CODE);
	        return;
	      }
	      
	      successFun(returnData.OUT_DATA);
	    },
	    error : function(textStatus) {
	    	modalObj.modal('close');
	        alert("网络或服务器异常，请稍后再试！");
	        console.info("request error:");
	    }
	  });
	};

/*
封装ws请求
*/
var sendWsPostAjax = function(params,reqUrl,successFun,loadingBarId){
  console.log("request url = "+reqUrl);
  console.log("request params = "+JSON.stringify(params));
  $.ajax({
    type: "post",
    contentType: "application/json",
    data: JSON.stringify(params),
    url: reqUrl,
    dataType: "json",
    async: true,
    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        console.log(data);
        var returnData = data.return;
        if(data.rtnCode!=1000){
          showLoadingBar($("#"+loadingBarId),true,true,data.rtnMsg);
          console.log("获取RPC接口返回失败！code:"+data.rtnCode);
          return;
        }
        if(returnData.resultCode!="00"){
          showLoadingBar($("#"+loadingBarId),true,true,returnData.resultDesc);
          console.log("获取信息接口返回失败！code:"+returnData.resultCode);
          return;
        }
        
        successFun(returnData);
    },
    error : function(textStatus) {
      showLoadingBar($("#"+loadingBarId),true,true,"网络或服务器异常，请稍后再试！");
      console.log("request error:");
    }
  });
};

var sendDzgPostAjax = function(params,reqUrl,successFun,loadingBarId){
	  console.log("request url = "+reqUrl);
	  console.log("request params = "+JSON.stringify(params));
	  $.ajax({
	    type: "post",
	    data: params,
	    url: reqUrl,
	    dataType: "json",
	    async: true,
	    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
	        console.log(data);
	        var returnData = data.data;
	        if(data.resultCode!=1000){
	          showLoadingBar($("#"+loadingBarId),true,true,data.message);
	          console.log("接口返回失败！code:"+data.resultCode);
	          return;
	        }
          
	        successFun(returnData);
	    },
	    error : function(textStatus) {
	      showLoadingBar($("#"+loadingBarId),true,true,"网络或服务器异常，请稍后再试！");
	      console.log("request error:");
	    }
	  });
	};
var sendRestPostAjax = function(params,reqUrl,successFun,loadingBarId){
  $.ajax({
    type: "post",
    data: params,
    url: reqUrl,
    dataType: "json",
    async: true,
    headers: {
    'token': getParamValue('token'),
    'saleType': getParamValue('saleType')
  },
  success: function(data) {
    if (data.ResultCode === 1009) {
      alert('登陆超时，请重新登录！');
      jumpToSignin();
      return;
    }
        console.log(data);
        var returnData = data.Data;
        if(data.ResultCode!=1000){
          showLoadingBar($("#"+loadingBarId),true,true,data.Message);
          console.log("接口返回失败！code:"+data.ResultCode);
          return;
        }
        
        successFun(returnData);
    },
    error : function(textStatus) {
      showLoadingBar($("#"+loadingBarId),true,true,"网络或服务器异常，请稍后再试！");
      console.log("request error:");
    }
  });
};
var checkCmccPhone = function(phone) {
		var reg = Constants.cmccMobileReg;
		if (reg.test(phone)) {
			return true;
		}
		return false;
};

var checkNumber = function(value) {
	var reg = Constants.number;
	if (reg.test(value)) {
		return true;
	}
	return false;
};

var showBtnProgress =function(btnId,start,msg){
	if(start){
		btnId.html("<i class='am-icon-spinner am-icon-spin'></i>&nbsp&nbsp&nbsp&nbsp"+msg);
		if(!btnId.hasClass("am-disabled")){
			btnId.addClass("am-disabled");
		}
	}else{
		btnId.html(msg);
       	if(btnId.hasClass("am-disabled")){
       		btnId.removeClass("am-disabled");
    	}
	}
}

/*
* 统计PV
* userid 用户ID
* module 模块名称，有统一映射关系表
* time 浏览时间
*/
var pageView = function(module){
  var params = {
	// 需要确认一下URL中是否包含userId
	userid: getParamValue("userId"),
	// 需要与后台统一module映射关系
	module: module,
	// 需要 include utils.js
	time: new Date().format("yyyy-MM-dd hh:mm:ss")
  };
  var res = JSON.stringify(params);
  
  var url = baseUrl + "/report/pageview/commit";
  //var url = "http://120.27.128.207/dzg/report/pageview/commit";
  $.ajax({
    type: "post",
    contentType:'application/json; charset=UTF-8',
	data: JSON.stringify(params),
    url: url,
    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
    	
    },
    error : function(data) {
    
    }
  });
};

/**
是否Android系统
*/
var isAndroid = function() { // android系统
  return /android|linux/i.test(window.navigator.userAgent + window.navigator.platform);
};
/**
是否IOS系统
*/
var isIOS = function() { // IOS系统
  return /iphone|ipad|ipod/i.test(window.navigator.userAgent + window.navigator.platform);
};

/**
 *  跳转到登录页面的逻辑，传值为'1'，这个参数方便以后有扩展 
*/
var jumpToSignin = function() {
  if (isIOS() && window.webkit && window.webkit.messageHandlers) {
    window.webkit.messageHandlers.jumpToSignin.postMessage('1');
  } else if (isAndroid() && window.client) {
    window.client.jumpToSignin('1');
  }
};
/**
* 日期格式化
* 例：dateFormat(new Date(), "YYYY/MM/DD hh:mm:ss S");
* 支持格式YYYY,yyyy; MM; DD,dd; HH,hh; mm; ss, S(毫秒)
*/
var dateFormat = function (date, fmt) {
    if(!(date instanceof Date)) date = new Date(date);
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/i.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if((["d+", "h+"].indexOf(k) === -1 ? new RegExp("("+k+")") : new RegExp("("+k+")", "i")).test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};